package com.zhp.controller.user;


import com.zhp.common.Constant;
import com.zhp.controller.BaseController;
import com.zhp.model.Dept;
import com.zhp.model.User;
import com.zhp.model.UserFocus;
import com.zhp.model.UserInfo;
import com.zhp.service.DeptService;
import com.zhp.service.UserInfoService;
import com.zhp.service.UserService;
import com.zhp.service.impl.DeptServiceImpl;
import com.zhp.service.impl.UserInfoServiceImpl;
import com.zhp.service.impl.UserServiceImpl;
import com.zhp.utils.PageUtil;
import com.zhp.utils.SrtUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/user/*")
public class UserController extends BaseController {

    private UserService userService = new UserServiceImpl();
    private DeptService deptService = new DeptServiceImpl();
    private UserInfoService userInfoService = new UserInfoServiceImpl();

    public void look(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String id = String.valueOf(req.getSession().getAttribute(req.getSession().getId()));
            UserInfo userInfo = userInfoService.findById(Integer.valueOf(id));
            userInfo.setLook(userInfo.getLook()+1);
            userInfoService.update(userInfo);  //更新浏览次数

            Map<String, Object> map = userService.getUserInfo(id);
            List<Dept> deptList = deptService.getAll();
            req.setAttribute("userInfo", map);
            req.setAttribute("deptList", deptList);
            req.getRequestDispatcher("/assets/html/user_look.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void getUsers(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String page = req.getParameter("page");
            String name = req.getParameter("searchName");
            int currentPage = 1;
            if (null != page) {
                currentPage = Integer.parseInt(page);
            }
//          从会话拿到当前用户得Id
            Map userinfo = (Map) req.getSession().getAttribute("userinfomap");
            String userId = userinfo.get("userId").toString();
            List<Map<String, Object>> userList = userService.getUserList(userId, currentPage, name);
            req.setAttribute("userList", userList);
            long totalCount = userService.getUserCount(name);
            long totalPage = PageUtil.getTotalPage(totalCount);
            long startPage = PageUtil.getStratPage(currentPage);
            long endPage = PageUtil.getEndPage(currentPage, totalCount);
            req.setAttribute("currentPage", currentPage);
            req.setAttribute("searchName", name);
            req.setAttribute("totalCount", totalCount);
            req.setAttribute("totalPage", totalPage);
            req.setAttribute("pageCount", Constant.PAGE_COUNT);
            req.setAttribute("startPage", startPage);
            req.setAttribute("endPage", endPage);
            req.getRequestDispatcher("/assets/html/user.jsp").forward(req, resp);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void followUser(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String data;
            String ufid = req.getParameter("ufid");
            String userId = getUserId(req);

            if (userId.equals(ufid)) {
                data = "不能关注自己";
            } else {

                //检查有没有重复关注
                UserFocus userFocus = userService.getFollowUser(userId, ufid);
                if (userFocus != null) {
                    //说明已经关注过了
                    data = "不能重复关注";
                } else {
                    boolean b = userService.followUser(userId, ufid);
                    if (b) {
                        data = "1";
                    } else {
                        data = "关注失败";
                    }
                }
            }
            resp.getWriter().write(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void unFollowUser(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String data;
            String ufid = req.getParameter("ufid");
            String userId = getUserId(req);
            UserFocus userFocus = userService.getFollowUser(userId, ufid);
            if (userFocus != null) {
                boolean b = userService.unFollowUser(userFocus.getId());
                if (b) {
                    data = "1";
                } else {
                    data = "取消关注失败";
                }
            } else {
                data = "你未关注过，无法取消";
            }
            resp.getWriter().write(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void updateUser(HttpServletRequest req, HttpServletResponse resp) {
        String realName = req.getParameter("real_name");
        String deptId = req.getParameter("dept_id");
        String phone = req.getParameter("phone");
        String age = req.getParameter("age");
        String sex = req.getParameter("sex");
        String isSecret = "1".equals(req.getParameter("is_secret")) ? "1" : "0";
        String myUserId = (String) req.getSession().getAttribute(req.getSession().getId());
        User user = userService.findById(Integer.parseInt(myUserId));
        UserInfo userInfo = userInfoService.findById(Integer.valueOf(myUserId));//查看用户详情
        if (!"".equals(realName)) {
            userInfo.setRealName(realName);
        }
        if (!"".equals(deptId)) {
            user.setDeptId(Integer.valueOf(deptId));
        }
        if (!"".equals(phone)) {
            userInfo.setPhone(phone);
        }
        if (!"".equals(age)) {
            userInfo.setAge(Integer.valueOf(age));
        }
        if (!"".equals(sex)) {
            userInfo.setGender(sex);
        }
        user.setIsSecret(isSecret);
        userInfo.setLook(userInfo.getLook()+1);
        int userrow = userService.update(user);
        int inforow = userInfoService.update(userInfo);
        if (userrow > 0 && inforow > 0) {
            try {
                req.getRequestDispatcher("/user/look").forward(req, resp);
            } catch (ServletException | IOException e) {
                e.printStackTrace();
            }
        }


    }

    public void uploadFile(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String data = "1";
            InputStream is = null;
            FileOutputStream fos = null;
            //工具类生成文件名
            String fileName = SrtUtil.getUUID() + Constant.IMG_SUFFIX;
            try {
                ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
                List<FileItem> items = servletFileUpload.parseRequest(req);
                if (!items.isEmpty()) {
                    FileItem file = items.get(0);
                    String name = file.getName();
                    if (!name.contains("jpg")) {
                        Map map = (Map) req.getSession().getAttribute("userinfomap");
                        String pic = (String) map.get("pic");
                        if (pic != null) {
                            resp.getWriter().write(req.getContextPath() + Constant.DEFAULT_PATH);
                        } else {
                            resp.getWriter().write(pic);
                        }
                        return;
                    }
                    is = file.getInputStream();
                    //虚拟路劲
                    fos = new FileOutputStream(Constant.FILE_PATH + fileName);
                    byte[] bytes = new byte[4 * 1024];
                    int len;
                    while (-1 != (len = is.read(bytes))) {
                        fos.write(bytes, 0, len);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (null != fos) {
                    fos.close();
                }
                if (null != is) {
                    is.close();
                }
            }
            //下一步，改数据库,和 会话
            String userId = getUserId(req);
            userService.uploadImg(userId, Constant.IN_PATH + fileName);
            Map map = (Map) req.getSession().getAttribute("userinfomap");
            Map<String, Object> userinfomap = userService.findUserBaseInfo(String.valueOf(map.get("username")));
            req.getSession().setAttribute("userinfomap", userinfomap);
            data = Constant.IN_PATH + fileName;
            resp.getWriter().write(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void myUserFocus(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String id = String.valueOf(req.getSession().getAttribute(req.getSession().getId()));
            String page = req.getParameter("page");
            int currentPage = 1;
            if (null != page) {
                currentPage = Integer.parseInt(page);
            }
            List<User> focusList = userService.getFocus(id,currentPage);
            Number totalCount = userService.getFocusAll(id);
            req.setAttribute("focusList", focusList);
            long totalPage = PageUtil.getTotalPage((Long) totalCount);
            long startPage = PageUtil.getStratPage(currentPage);
            long endPage = PageUtil.getEndPage(currentPage, (Long) totalCount);
            req.setAttribute("currentPage", currentPage);
            req.setAttribute("totalCount",totalCount);
            req.setAttribute("totalPage", totalPage);
            req.setAttribute("pageCount", Constant.PAGE_COUNT);
            req.setAttribute("startPage", startPage);
            req.setAttribute("endPage", endPage);
            req.getRequestDispatcher("/assets/html/my_user.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void detail(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String id = String.valueOf(req.getParameter("id"));

            UserInfo userInfo = userInfoService.findById(Integer.valueOf(id));
            userInfo.setLook(userInfo.getLook()+1);
            userInfoService.update(userInfo);  //更新浏览次数

            Map<String, Object> map = userService.getUserInfo(id);
            List<Dept> deptList = deptService.getAll();
            req.setAttribute("userInfo", map);
            req.setAttribute("deptList", deptList);
            req.getRequestDispatcher("/assets/html/user_detail.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
